import fs from 'fs';
import { resolve } from 'path';
import { STYLE_SUB_IDENTIFIER } from './src/constants/index.ts';

const lib = resolve('./lib');

const log = (...par: any[]) => {
  console.log('\x1B[33m%s  \x1B[32m%s\x1B[0m', ...par);
}

if (fs.existsSync(lib)) {
  fs.rmSync(lib, { force: true, recursive: true });
}
fs.mkdirSync(lib);

const dist = resolve('./dist');
const files = fs.readdirSync(dist);
const jsFile = files.filter(name => name.endsWith('.js') || name.endsWith('.cjs')).pop();
const cssFile = files.filter(name => name.endsWith('.css')).pop();

const cssCtx = fs.readFileSync(resolve(dist, cssFile!), 'utf-8').replace(/[\n]/g, '');
log('[✓][readed]', cssFile);

const jsCtx = fs
  .readFileSync(resolve(dist, jsFile!), 'utf-8')
  .replace(/\(function\(\)\{.*\}\)\(\);/g, '')
  .replace(STYLE_SUB_IDENTIFIER, cssCtx);

log('[✓][readed]', jsFile);
log('[✓][merged]', 'css file and js file');

const packageCtx = fs.readFileSync(resolve('./package.json'), 'utf-8');
const packageJson = JSON.parse(packageCtx);

const jScript = `// ==UserScript==
// @name          B站视频下载器(RPC)
// @namespace     https://gitee.com/ameegle/bilibili
// @version       ${packageJson.version}
// @description   使用PRC链接Motrix的方式
// @author        ameegle
// @license       ISC
// @source        https://gitee.com/ameegle/bilibili/raw/main/lib/bilibili.js
// @match         *://www.bilibili.com/festival/*
// @match         *://www.bilibili.com/video/av*
// @match         *://www.bilibili.com/video/BV*
// @match         *://www.bilibili.com/list/*
// @match         *://www.bilibili.com/bangumi/play/ep*
// @match         *://www.bilibili.com/bangumi/play/ss*
// @match         *://www.bilibili.com/cheese/play/ep*
// @match         *://www.bilibili.com/cheese/play/ss*
// ==/UserScript==
(function(){\n${jsCtx.replace(/\/\* @__PURE__ \*\/\s?/g, '')}})();
`

const outFileName = 'bilibili.js';
const outPath = resolve(lib, outFileName);

fs.writeFileSync(outPath, jScript, 'utf-8');
log('[✓][created]', ['lib', outFileName].join('/'));